import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
  SearchOutlined,
  UndoOutlined, CheckOutlined
} from '@ant-design/icons';
import {
  Button,
  message,
  Form,
  DatePicker,
  Upload,
  Modal,
  Row,
  Col,
  Input,
  Popconfirm,
  Select, Space,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProForm, { ProFormTextArea, ProFormText } from '@ant-design/pro-form';
import { useForm } from 'antd/es/form/Form';
import ProTable from '@ant-design/pro-table';
import '@/assets/css/index.less';
import {
  deletePhotoById,
  getPhotoCategoryList,
  getPhotoFile,
  getPhotoList,
} from '@/services/pictureManager';
import { history } from 'umi';
import formatDate from '@/utils/formatDate';
import moment from 'moment';
import {
  batchDeleteIP,
  deleteBlackList,
  deleteIP,
  getBlackList,
  getIpList,
  insertBlackList,
  insertIP,
  updateBlackList,
} from '@/services/ipmanager';
const { RangePicker } = DatePicker;

const formLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
};
const IPManagement: React.FC = () => {
  const [form] = Form.useForm();
  const [search_form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [formTarget, setFormTarget] = useState('');
  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={search_form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="IP" name="ip_search">
                <Input placeholder="请输入IP" onChange={() => queryData()} />
              </Form.Item>
            </Col>

            <Col span={8}>
              <Form.Item label="操作时间" name="dateTime">
                <RangePicker onChange={() => queryData()} />
              </Form.Item>
            </Col>

            <Col
              span={12}
              className="basic-search-form-submit-btn"
              style={{ display: 'flex', justifyContent: 'flex-end' }}
            >
              <Button
                onClick={() => {
                  search_form.resetFields();
                  queryData();
                }}
              >
                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };
  const actionRef = useRef<ActionType>();
  const [selectedRows, setSelectedRows] = useState([]);
  const [currentValue, setCurrentValue] = useState();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(40);
  const [dataArray, setDataArray] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });
  const handleDelete = async (record: any) => {
    try {
      const res = await deleteIP({ ip: record.ip });
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败！' + error.response.data.message);
    }
    queryData();
  };
  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
    setPagination({ ...pagination });
  };
  const onSubmit = async (values) => {
    let res = {};
    try {
      res = await insertIP({
        ip: values.ip,
      });
      message.success('添加成功！');
      queryData();
    } catch (error) {
      console.log(error);

      message.error('添加失败！' + error.response.data.message);
    }
    setModalVisible(false);
  };

  useEffect(() => {
    queryData();
  }, [page, pageSize]);

  const queryData = async () => {
    let values = search_form.getFieldsValue();
    if (values.dateTime != null && values.dateTime != undefined) {
      values.timeStart = moment(values.dateTime[0]).format('YYYY-MM-DD') + ' 00:00:00';
      values.timeEnd = moment(values.dateTime[1]).format('YYYY-MM-DD') + ' 23:59:59';
    }

    const params = {
      page: page,
      pageSize: pageSize,
    };

    values = values && JSON.parse(JSON.stringify(values).replace('ip_search', 'ip'));
    const msg = await getIpList(params, values);
    setDataArray(msg.data.list);
    setPagination({ ...pagination, total: msg.data.total });
  };
  const hideTableAlert = () => {
    const tableAlertElement = document.querySelector('.ant-pro-table-alert');
    tableAlertElement.setAttribute('style', 'display: none');
  };
  const batchRemove = async (selectedRows: any) => {
    if (!selectedRows || selectedRows.length === 0) {
      message.error('请选择所要删除的行！');
      return;
    }
    let ipArray = [];
    selectedRows.forEach((element) => {
      ipArray.push(element.ip);
    });
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      await batchDeleteIP(ipArray);
      hide();
      queryData();

      message.success('已删除！');
      hideTableAlert();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败！' + error.response.data.message);
      hideTableAlert();
      return false;
    }
  };
  const columns: ProColumns[] = [
    {
      title: 'IP',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'ip',
    },

    {
      title: '添加时间',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdTime',
    },
    {
      title: '添加人',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdBy',
    },
    {
      title: '操作',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'id',
      render: (_, record) => [
        <Popconfirm title="确定是否删除?" onConfirm={() => handleDelete(record)} key="delete">
          <a style={{ color: 'red' }}>
            <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
              删除
            </Button>
          </a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <PageContainer>
      {_initSearchForm()}
      <ProTable
        search={false}
        // headerTitle="视媒管理"
        actionRef={actionRef}
        rowKey="ip"
        tableStyle={{ textAlign: 'center' }}
        options={false}
        pagination={pagination}
        onChange={handleTableChange}
        dataSource={dataArray}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setModalVisible(true);
              setFormTarget('add');
            }}
          >
            <PlusOutlined />
            添加
          </Button>,
          <Popconfirm
            title="确定是否批量删除?"
            onConfirm={() => batchRemove(selectedRows)}
            key="delete"
          >
            <Button type="primary" key="primay" danger>
              <PlusOutlined />
              批量删除
            </Button>
          </Popconfirm>,
        ]}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      ></ProTable>
      <Modal
        title={formTarget === 'edit' ? '编辑限制IP' : '添加限制IP'}
        width="600px"
        destroyOnClose
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
        }}
        footer={null}
      >
        <ProForm
          form={form}
          layout="horizontal"
          {...formLayout}
          initialValues={''}
          onFinish={onSubmit}
          onReset={() => {}}
          submitter={{
            render: (_, dom) => (
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <Space>
                  {/*{dom}*/}
                  {<Button onClick={() => {
                    _.reset()
                  }}><UndoOutlined />重置</Button>}
                  {<Button type={"primary"} onClick={() => {
                    _.submit()
                  }}><CheckOutlined />提交</Button>}

                </Space>
              </div>
            ),
          }}
        >
          <ProFormText
            rules={[
              {
                required: true,
                message: '限制IP必填！',
              },
            ]}
            width="md"
            name="ip"
            placeholder="请输入限制IP"
            label="限制IP"
          />
        </ProForm>
      </Modal>
    </PageContainer>
  );
};
export default IPManagement;
